package net.butfly.bus.filter;

import java.util.ArrayList;
import java.util.List;

import net.butfly.albacore.exception.SystemException;
import net.butfly.bus.Constants;
import net.butfly.bus.Constants.FilterSide;
import net.butfly.bus.Request;
import net.butfly.bus.Response;
import net.butfly.bus.config.bean.FilterBean;

public final class FilterChain {
	private Filter[] filters;

	public FilterChain(List<FilterBean> beans, Filter main, FilterSide side) {
		List<Filter> filters = new ArrayList<Filter>();
		if (beans == null)
			beans = new ArrayList<FilterBean>();
		for (FilterBean bean : beans) {
			bean.getFilter().initialize(bean.getParams());
			this.addFilter(filters, bean.getFilter(), side);
		}
		this.addFilter(filters, main, side);
		this.filters = filters.toArray(new Filter[filters.size()]);
	}

	private void addFilter(List<Filter> list, Filter filter, FilterSide side) {
		((FilterBase) filter).chain = this;
		filter.setSide(side);
		list.add(filter);
	}

	public void execute(Request request, Response response) throws Exception {
		this.filters[0].execute(request, response);
	}

	void execute(Filter current, Request request, Response response) throws Exception {
		int pos = -1;
		for (int i = 0; i < this.filters.length; i++)
			if (this.filters[i].equals(current)) {
				pos = i;
				break;
			}
		if (pos == -1) // not found
			throw new SystemException(Constants.BusinessError.INVOKE_ERROR, "找不到过滤器");
		if (pos == this.filters.length - 1) // last
			return;
		this.filters[pos + 1].execute(request, response);
	}
}
